package com.qingmu.club.minaapi.utils;

import com.alibaba.fastjson.JSONObject;
import com.qingmu.club.minaapi.model.AddressModel;
import com.qingmu.club.minaapi.model.LatlgtPoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class AddressUtil {

  public static AddressModel getAddr(String lng, String lat) throws IOException {


      String url = "http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location="+lat+","+lng+"&output=json&pois=1&ak=yG6ODsyIljZHHjj2TXOUVkApYdv3IyuZ";
      URL myURL = null;

      String city = "";
      String country="";
      String street="";
      String province="";
      String district="";

      AddressModel addressModel = new AddressModel();

      URLConnection httpsConn = null;
      try {
          myURL = new URL(url);
      } catch (MalformedURLException e) {
          e.printStackTrace();
      }
      InputStreamReader insr = null;
      BufferedReader br = null;
      try {
          httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
          if (httpsConn != null) {
              insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
              br = new BufferedReader(insr);
              String data = null;
              while ((data = br.readLine()) != null) {
                  data=data.substring(data.indexOf("(")+1,data.lastIndexOf(")"));
                  System.out.println("date："+data);
                  JSONObject json = JSONObject.parseObject(data);
                  lng = json.getJSONObject("result").getJSONObject("location").getString("lng");
                  lat = json.getJSONObject("result").getJSONObject("location").getString("lat");
                  country = json.getJSONObject("result").getJSONObject("addressComponent").getString("country");
                  province = json.getJSONObject("result").getJSONObject("addressComponent").getString("province");
                  city = json.getJSONObject("result").getJSONObject("addressComponent").getString("city");
                  district = json.getJSONObject("result").getJSONObject("addressComponent").getString("district");
                  street = json.getJSONObject("result").getJSONObject("addressComponent").getString("street");


                  addressModel.setCountry(country);
                  addressModel.setProvince(province);
                  addressModel.setCity(city);
                  addressModel.setDistrict(district);
                  addressModel.setStreet(street);
                  addressModel.setLat(lat);
                  addressModel.setLng(lng);
              }
          }
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
          if (insr != null) {
              insr.close();
          }
          if (br != null) {
              br.close();
          }
      }
      return addressModel;
  }


   //根据地址获取经纬度
    public static LatlgtPoint getCoordinate(String addr){
        String lng = null;//经度
        String lat = null;//纬度
        String address = null;
        try {
            address = java.net.URLEncoder.encode(addr, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String key = "f247cdb592eb43ebac6ccd27f796e2d2";
        String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStreamReader insr = null;
        BufferedReader br = null;
        try {
            httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
            if (httpsConn != null) {
                insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
                br = new BufferedReader(insr);
                String data = null;
                int count = 1;
                while ((data = br.readLine()) != null) {
                    if (count == 5) {
                        lng = (String) data.subSequence(data.indexOf(":") + 1, data.indexOf(","));//经度
                        count++;
                    } else if (count == 6) {
                        lat = data.substring(data.indexOf(":") + 1);//纬度
                        count++;
                    } else {
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        LatlgtPoint latlgtPoint = new LatlgtPoint();
        latlgtPoint.setLat(lat);
        latlgtPoint.setLng(lng);

        return latlgtPoint;
    }

    private static double degrees(double d) {

        return d * (180 / Math.PI);

    }

    private static final double EARTH_RADIUS = 6378137;

    private static double rad(double d) {

        return d * Math.PI / 180.0;

    }


    /**
     * 传入经纬度计算距离，单位为km,保留2位小数
     *
     * @param lng1
     * @param lat1
     * @param lng2
     * @param lat2
     * @return
     */
    public static String calDistance(double lng1, double lat1, double lng2, double lat2) {

        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS / 1000;

        return  String.format("%.2f", s);

    }

    /**
     * @param lat  纬度
     * @param lon  经度
     * @param distance  单位km
     * @return
     */
    public static Map<String,Double> getDistance(double lat , double lon , double distance) {

        //先计算查询点的经纬度范围
        double r = 6378.137;//地球半径千米
        double dis = distance;//千米距离
        double dlng = 2 * Math.asin(Math.sin(dis / (2 * r)) / Math.cos(lat * Math.PI / 180));
        dlng = dlng * 180 / Math.PI;//角度转为弧度
        double dlat = dis / r;
        dlat = dlat * 180 / Math.PI;
        double minLat = lat - dlat;
        double maxLat = lat + dlat;
        double minLon = lon - dlng;
        double maxLon = lon + dlng;

        Map<String ,Double> map = new HashMap<>();
        map.put("minLat",minLat);
        map.put("maxLat",maxLat);
        map.put("minLon",minLon);
        map.put("maxLon",maxLon);

        return map;
    }

}
